package ar.mobileideas.mobiletasks.api.webservice;

import java.util.Enumeration;
import java.util.Hashtable;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;

public class MobileTasksService {
	
	private static String ServiceUrl;
	private static String ServiceNamespace;
	
	SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

	public static void Initialize(String serviceUrl, String serviceNamespace)
	{
		MobileTasksService.ServiceUrl = serviceUrl;
		MobileTasksService.ServiceNamespace = serviceNamespace;
	}
	
	public static String CallWebServiceMethod(String methodName, Hashtable parameters)
	{
		String soapAction = MobileTasksService.ServiceNamespace + methodName;
		SoapObject soapObject = new SoapObject(MobileTasksService.ServiceNamespace, methodName);
		
		Enumeration keys = parameters.keys();
		
		while( keys.hasMoreElements() ) {
		  Object key = keys.nextElement();
		  Object value = parameters.get(key);
		  
		  soapObject.addProperty(key.toString(),value.toString());
		}
		
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

		envelope.bodyOut = soapObject;
		envelope.dotNet = true;
		envelope.encodingStyle = SoapSerializationEnvelope.XSD;

		HttpTransport ht = new HttpTransport(MobileTasksService.ServiceUrl);
		ht.debug = true;
		ht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

		String result = null;

		try
		{
			ht.call(soapAction, envelope);
			result = envelope.getResponse().toString();
			
			return result;
		}
		catch(org.xmlpull.v1.XmlPullParserException ex2){
			return ex2.getMessage();
		}
		catch(Exception ex){
			return ex.getMessage();
		}
		
	}
	
	public static String GetResponseKeyValue(String key, String response) {
		String start = "anyType{" + key + "=";
		String end = "; }";
	 
		if (response.indexOf(start) == -1 ||
			response.indexOf(end) == -1) return "";
	 
		response = response.substring(response.indexOf(start) + start.length());
		response = response.substring(0, response.indexOf(end));
	 
		if (response.indexOf("anyType{}") != -1) return "";
	 
		return response;
	}
}
